//
//  HREmotionView.swift
//  weiBo
//
//  Created by helong on 16/7/19.
//  Copyright © 2016年 helong. All rights reserved.
//

/// 自定一键盘视图类
import UIKit
//  toolbar的类型枚举
enum ToolBarType: Int {
    //  枚举的原始值如果为 0 ,当使用tag去控件的时候会有bug 因为默认控件的tag值就为0,取到的是自己
    case Default = 1000
    case Emoji = 1001
    case LXH = 1002
}
class HREmotionView: UIView {
    //  cell的重用标示符
    let EmotionCellIdentifier = "EmotionCellIdentifier"
    //  记录按钮状态
    private var recordButton: UIButton?
    //  点击底部按钮的闭包
    var emotionButtonClicked: ((type: ToolBarType) -> ())?
    
    //  懒加载键盘底部区块
    private lazy var toolBar: UIStackView = {
        let view = UIStackView()
        view.distribution = .FillEqually
        view.axis = .Horizontal
        return view
    }()
    
    //  懒加载表情键盘区
    private lazy var emotionCollectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        //  设置数据源和代理
        collectionView.dataSource = self
        collectionView.delegate = self
        //  不显示滚动知识条
        collectionView.showsHorizontalScrollIndicator = false
        //  打开分页
        collectionView.pagingEnabled = true
        //  关闭弹簧效果
        collectionView.bounces = false
        collectionView.backgroundColor = UIColor.whiteColor()
        return collectionView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

     // MARK: - 计算frame
    override func layoutSubviews() {
        super.layoutSubviews()
        //  获取flowlayout
        let flowLayout = emotionCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        //  设置大小
        flowLayout.itemSize = emotionCollectionView.bounds.size
        //  滚动方向
        flowLayout.scrollDirection = .Horizontal
        //  水平,垂直间距
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

     // MARK: -  设置UI
    private func setupUI(){
        
        //  创建底部的三个按钮
       recordButton = addChildButton("默认", type: .Default, imageName: "compose_emotion_table_", location: "left")
        // 默认选中默认按钮
        recordButton?.selected = true
        addChildButton("Emoji", type: .Emoji, imageName: "compose_emotion_table_", location: "mid")
        addChildButton("浪小花", type: .LXH, imageName: "compose_emotion_table_", location: "right")
        backgroundColor = randomColor()
        
        //  注册cell
        emotionCollectionView.registerClass(HREmotionCollectionViewCell.self, forCellWithReuseIdentifier: EmotionCellIdentifier)
        
        addSubview(toolBar)
        addSubview(emotionCollectionView)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.bottom.equalTo(self)
        }
        emotionCollectionView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.top.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
    }
    
     // MARK: - 自定义创建按钮的额方式
    private func addChildButton(title: String, type: ToolBarType, imageName: String, location: String) -> UIButton {
        let btn = UIButton()

        btn.setTitle(title, forState: .Normal)
        btn.tag = type.rawValue
        btn.setBackgroundImage(UIImage(named: imageName + location + "_normal"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: imageName + location + "_selected"), forState: .Selected)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.grayColor(), forState: .Selected)
        //  取消按钮的高亮效果
        btn.adjustsImageWhenHighlighted = false
        //  添加点击事件
        btn.addTarget(self, action: "toolBarClicked:", forControlEvents: .TouchUpInside)
        //  添加到stackview中
        toolBar.addArrangedSubview(btn)
        return btn
    }
    
     // MARK: - toolbar按钮的点击事件
    @objc private func toolBarClicked(sender: UIButton) {
        //  如果已经是选中就不在选中
        if sender.selected {
            return
        }
        recordButton?.selected = false
        sender.selected = true
        recordButton = sender
        
        //  调用闭包
        //        emotionButtonClicked?(type: type!)
        let type = ToolBarType(rawValue: sender.tag)!
        //  滚动表情键盘的方法
        scrollToIndexPath(type)
     
    }

     // MARK: - 滚动表情键盘的方法
    private func scrollToIndexPath(type: ToolBarType){
        var indexPath = NSIndexPath(forItem: 0, inSection: 0)
        switch type {
        case .Default:
            print("默认")
            indexPath = NSIndexPath(forItem: 0, inSection: 0)
            emotionCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        case .Emoji:
            indexPath = NSIndexPath(forItem: 0, inSection: 1)
            print("emoji")
            emotionCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        case .LXH:
            indexPath = NSIndexPath(forItem: 0, inSection: 2)
            print("浪小花")
            emotionCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        }
    }
    
     // MARK: - 根据cell的section让对应按钮选中
    private func selectedButtonWithSection(section: Int) {
        //  通过section作为tag值获取按钮
        let btn = viewWithTag(section + 1000) as! UIButton
        //  如果已经选中就不要在选中了
        if recordButton == btn {
            return
        }
        recordButton?.selected = false
        btn.selected = true
        recordButton = btn
    }

}
 // MARK: - uicollectionview 的数据源和代理方法
extension HREmotionView: UICollectionViewDataSource, UICollectionViewDelegate {
     // MARK: - 三个数据源方法
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return HREmotionManager.manager.emotionsArray.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HREmotionManager.manager.emotionsArray[section].count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmotionCellIdentifier, forIndexPath: indexPath) as! HREmotionCollectionViewCell
        cell.emotion = HREmotionManager.manager.emotionsArray[indexPath.section][indexPath.item]
        return cell
    }
     // MARK: - 滚动的方法
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //  把可见的cell按照 X 从小到大排列,可见的cell永远最多只有两个
       let cell = (scrollView as! UICollectionView).visibleCells().sort { (firstCell, secondCell) -> Bool in
        return firstCell.x < secondCell.x
        }
        
        //  如果有两个可见的cell,判断哪个显示的多
        if cell.count == 2 {
            let firstCell = cell.first!
            let secondCell = cell.last!
            let firstContentOffsetX = abs((firstCell.x) - scrollView.contentOffset.x)
            let secondContentOffsetX = abs((secondCell.x) - scrollView.contentOffset.x)
        //  判断滚动是否过半
            let myCell: UICollectionViewCell
        if firstContentOffsetX > secondContentOffsetX {
            myCell = secondCell
        }else{
            myCell = firstCell
            }
            let indexPath = emotionCollectionView.indexPathForCell(myCell)!
            //  根据cell的indexpath让表情分组按钮对应显示
            selectedButtonWithSection(indexPath.section)
        }
        
    }
}
















